//
//  RCChoosePictureController.swift
//  RC-微博0305
//
//  Created by 任淳 on 16/3/16.
//  Copyright © 2016年 ReverChun. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

let comCellCount:CGFloat = 4
let cellMargin:CGFloat = 5

class RCChoosePictureController: UICollectionViewController {
    
    //选中图片的数组
    var imageArray = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(RCChoosePicCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        view.backgroundColor = UIColor.whiteColor()

    }

    //构造方法
    init() {
        
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = cellMargin
        layout.minimumLineSpacing = cellMargin
        layout.sectionInset = UIEdgeInsets(top: cellMargin, left: cellMargin, bottom: 0, right: cellMargin)
        let w = (screenWidth - (comCellCount + 1) * cellMargin) / comCellCount
        layout.itemSize = CGSize(width: w, height: w)
        
        super.init(collectionViewLayout: layout)
        
        self.collectionView!.backgroundColor = UIColor.whiteColor()

        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //最大数量3张 超过3  不让用户选
        let maxCount = 3
        
        let num = imageArray.count == maxCount ? 0 : 1
        
        return imageArray.count + num
        
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! RCChoosePicCell
        //设置cell颜色
        cell.backgroundColor = UIColor(red: CGFloat(random() % 256)/255.0, green:  CGFloat(random() % 256)/255.0, blue:  CGFloat(random() % 256)/255.0, alpha: 1)

        cell.delegate = self
        
        if indexPath.item == imageArray.count {
             //加载最后一个cell的时候  会执行这个分支
            cell.image = nil
        }else {
            
            cell.image = imageArray[indexPath.item]
        }
        
        return cell
    }


}

//控制器实现cell的代理方法
extension RCChoosePictureController:RCChoosePicCellDelegate {
    
    func userWillChoosePic(cell: RCChoosePicCell) {
        
        let pickerVc = UIImagePickerController()
        //要想把选中的图片显示到cell上 就要实现pickerVc的代理方法
        pickerVc.delegate = self
        //设置图片允许编辑  在上传用户头像的时候需要开启这个属性
//        picker.allowsEditing = true
        presentViewController(pickerVc, animated: true, completion: nil)
        
    }
    
    func userWillDeletePic(cell: RCChoosePicCell) {
        //选中cell的indexPath
        let index = collectionView?.indexPathForCell(cell)
        //移除当前这个cell的图片
        imageArray.removeAtIndex((index?.item)!)
        
        collectionView?.reloadData()
        
    }
    
}

//UIImagePickerController的代理类 必须遵守下面两个协议
extension RCChoosePictureController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //返回选中的图片image 用自己定义的数组接受一下
        imageArray.append(image)
        //刷新一下
        collectionView?.reloadData()
        
        //选完就回去 dismiss掉
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
}



//==================================================
//cell协议的声明
protocol RCChoosePicCellDelegate:NSObjectProtocol {
    
    func userWillChoosePic(cell:RCChoosePicCell)
    
    func userWillDeletePic(cell:RCChoosePicCell)
    
}


class RCChoosePicCell: UICollectionViewCell {
    
    //定义一个代理属性
    weak var delegate:RCChoosePicCellDelegate?
    
    var image:UIImage? {
        didSet{
            //没有图片 就隐藏删除按钮
            deleBtn.hidden = image == nil
            //一有照片 就把btn的背景换成图片
            addBtn.setImage(image, forState: .Normal)
        }
        
    }
    
    //添加图片方法
    func addBtnDidPush() {
        //执行代理方法
        //判断下 点击的btn没有图片再去选择  有了就不让选
        if image == nil {
            delegate?.userWillChoosePic(self)
        }
        
    }
    
    //删除图片方法
    func deleBtnDidPush() {
        delegate?.userWillDeletePic(self)
        
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
     
        addSubview(addBtn)
        addSubview(deleBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        
        deleBtn.snp_makeConstraints { (make) -> Void in
            make.right.top.equalTo(self)
        }
     
        addBtn.addTarget(self, action: "addBtnDidPush", forControlEvents:.TouchUpInside)
        deleBtn.addTarget(self, action: "deleBtnDidPush", forControlEvents: .TouchUpInside)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var addBtn:UIButton = UIFactory.btnWithImage("compose_pic_add", imageName: nil)
    
    lazy var deleBtn:UIButton = UIFactory.btnWithImage("compose_photo_close", imageName: nil)
    
    
    
}

